<?php

namespace app\admin\controller;

use app\admin\validate\WithdrawValidate;
use app\exception\CommonException;
use app\service\FinancialLogService;
use app\service\MemberCoinService;
use app\service\MemberService;
use app\service\WithdrawService;
use think\exception\ValidateException;

class Withdraw extends Admin
{
    public function __construct(WithdrawService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "提现列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where = [];
        if (!empty($params["create_at"])) {
            $between = explode(" - ", $params["create_at"]);
            if (count($between) == 2) {
                $where[] = ["create_at", "between", [$between[0], $between[1]]];
            }
        }
        $email = $params["email"];
        $memberId = $params["member_id"];
        $memberIds = [];
        if ($email) {
            $memberService = $this->app->make(MemberService::class);
            $memberIds = $memberService->Column([["email", "like", "%$email%"]], "id");
            if (empty($memberIds)) {
                $ret = ["rows" => [
                    "total" => 0,
                    "list" => [],
                ]];
                $this->result($ret);
            }
        }
        if (!empty($memberId)) {
            array_push($memberIds, $memberId);
        }
        if (!empty($memberIds)) {
            $where[] = ['member_id', 'in', $memberIds];
        }
        if (!empty($status)) {
            $where[] = ['status', '=', $status];
        }
        if (!empty($params["order_sn"])) {
            $where[] = ['order_sn', '=', $params["order_sn"]];
        }
        $ret = $this->service->getList($where, "*", ["member", "coin", "address"]);
        int_to_string($ret["rows"]["list"], ["status" => ["-1" => "驳回", "1" => "审核中", "2" => "通过"]]);
        $this->result($ret);
    }

    public function audit()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "审核");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id, ['*'], ["member", "coin", "address"]);
            $this->assign("vo", $vo);
            return $this->fetch("audit");
        }
        $params = $this->request->Post();
        $data["status"] = $params["status"];
        $data["id"] = $params["id"];
        $data["remark"] = $params["remark"];
        try {
            validate(WithdrawValidate::class)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $withdrawInfo = $this->service->get($params["id"], ["id", "member_id", "coin_id", "num", "fee"]);
        if (empty($withdrawInfo)) {
            throw new CommonException("提现记录不存在");
        }
        $memberId = $withdrawInfo->member_id;
        $amount = $withdrawInfo->num;
        $coinId = $withdrawInfo->coin_id;
        $fee = $withdrawInfo->fee;
        $financialLogService = $this->app->make(FinancialLogService::class);
        $memberCoinService = $this->app->make(MemberCoinService::class);
        $this->service->transaction(function () use ($memberId, $amount, $coinId, $financialLogService, $memberCoinService,$data,$fee) {
            if ($data["status"] == \app\model\Withdraw::WITHDRAW_STATUS_REJECTED) {
                $financialLogService->flowLog($memberId, $amount, $coinId, -$amount, \app\model\FinancialLog::WITHDRAW_REJECTED, "提现拒绝返回账户");
            } else {
                $memberCoinInfo = $memberCoinService->getOne(["member_id" => $memberId, "coin_id" => $coinId], "*");
                $frozenAmount = $memberCoinInfo->frozen_amount - $amount;
                $memberCoinService->save(["id" => $memberCoinInfo->id, "frozen_amount" => $frozenAmount]);
            }
            $this->service->save($data);
        });
        $this->success("审核成功");
    }
}